################################
# Dyadic Ratio algorithm: UK   #
# Appendix table3              #
################################


###load library
library(openxlsx)
library(psych)
library(ggplot2)
library(gridExtra)
library(tidyverse)

###usa macropartisanship_extract
# "extract.R" should be obtained from James Stimson's HP
# URL: https://stimson.web.unc.edu/software/

source("extract.R")

#load data
uk<-read.csv("uk_extract.csv")
attach(uk)
describe(uk)
uk<-na.omit(uk)

#make tidy data by tidyverse
df_uk_tidy <- uk %>%
  gather(key = VARNAME, value = value, -yearMon)

#setting time-series information
varname<-df_uk_tidy$VARNAME
date<-as.Date(df_uk_tidy$yearMon)
index<-df_uk_tidy$value
ncases<-NULL

#using "extract" to compute macropartisanship
output_uk<-extract(varname,date=date,index,ncases,begindt=ISOdate(1959,10,1),
                   enddt = ISOdate(2016,12,1), unit="A",npass=2)
display(output_uk)
summary(output_uk)

#factor scores of 2 dimensions
mpartisan1_uk<-output_uk$latent1
mpartisan2_uk<-output_uk$latent2
YEAR<-1959:2016



###-----plotting macropartisanship-----###

library(ggplot2)
df1<-data.frame(x=YEAR,y=mpartisan1_uk)


windows(16,8)
img<-ggplot(df1, aes(x = YEAR, y = mpartisan1_uk)) +
  geom_line(lwd=1.3) +
  xlab("Year") +
  ylab("macropartisanship with DRA (UK)") +
  ggtitle("")+
  scale_x_continuous(breaks = seq(1959, 2016, by = 5))+
  theme_bw()
print(img)



